<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            // preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
            var buildTree = function (preorder, inorder) {
                if (!inorder.length) return null
                //定义根节点
                let root = {
                    val: preorder[0],
                    left: null,
                    right: null
                }
                let mid = inorder.indexOf(root.val)
                //得出根节点是[3]  中序得出左子树是[9]  右子树[15,20,7]
                //所以前序需要从preorder中截取出[9] 和[15,20,7]的序列
                root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid))
                root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1))
                return root
            }
        </script>
    </body>
</html>
